package com.clei.utils.mqtt;

import com.clei.utils.PrintUtil;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Arrays;

/**
 * 默认回调处理
 *
 * @author Y
 * @date 2024-01-02
 **/
public class DefaultMqttMsgCallback implements MqttCallback {

    /**
     * reconnectTask
     */
    private Runnable reconnectTask;

    public void setReconnectTask(Runnable r) {
        this.reconnectTask = r;
    }

    public void connectionLost(Throwable cause) {
        PrintUtil.log("connectionLost", cause);
        reconnectTask.run();
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        PrintUtil.log("messageArrived topic : {}, msg : {}", topic, new String(message.getPayload()));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        try {
            PrintUtil.log("deliveryComplete topic : {}, msg : {}", Arrays.toString(token.getTopics()),
                    new String(token.getMessage().getPayload()));
        } catch (MqttException e) {
            PrintUtil.log("deliveryComplete", e);
        }
    }
}